<template>
  <div class="create-survey">
    <div class="header">
      <h2>创建问卷</h2>
      <el-button-group>
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button type="success" @click="handlePublish">发布</el-button>
        <el-button @click="$router.back()">取消</el-button>
      </el-button-group>
    </div>

    <el-form :model="surveyForm" label-width="120px" class="survey-form">
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-form-item label="问卷标题" required>
          <el-input v-model="surveyForm.title" placeholder="请输入问卷标题" />
        </el-form-item>
        
        <el-form-item label="问卷说明">
          <el-input
            v-model="surveyForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入问卷说明"
          />
        </el-form-item>
        
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="surveyForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
          />
        </el-form-item>
        
        <el-form-item label="问卷类型">
          <el-radio-group v-model="surveyForm.type">
            <el-radio label="public">公开问卷</el-radio>
            <el-radio label="private">私密问卷</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-card>

      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>问题列表</span>
            <el-button type="primary" @click="addQuestion">
              <el-icon><Plus /></el-icon>添加问题
            </el-button>
          </div>
        </template>

        <div v-for="(question, index) in surveyForm.questions" :key="index" class="question-item">
          <div class="question-header">
            <span class="question-title">问题 {{ index + 1 }}</span>
            <el-button-group>
              <el-button type="danger" size="small" @click="removeQuestion(index)">
                删除
              </el-button>
              <el-button type="primary" size="small" @click="moveQuestion(index, -1)" :disabled="index === 0">
                上移
              </el-button>
              <el-button type="primary" size="small" @click="moveQuestion(index, 1)" :disabled="index === surveyForm.questions.length - 1">
                下移
              </el-button>
            </el-button-group>
          </div>

          <el-form-item label="问题类型">
            <el-select v-model="question.type" placeholder="请选择问题类型">
              <el-option label="单选题" value="single" />
              <el-option label="多选题" value="multiple" />
              <el-option label="填空题" value="text" />
              <el-option label="评分题" value="rating" />
            </el-select>
          </el-form-item>

          <el-form-item label="问题内容" required>
            <el-input v-model="question.content" placeholder="请输入问题内容" />
          </el-form-item>

          <el-form-item v-if="['single', 'multiple'].includes(question.type)" label="选项">
            <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option-item">
              <el-input v-model="option.content" placeholder="请输入选项内容">
                <template #append>
                  <el-button @click="removeOption(question, optionIndex)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
            <el-button type="primary" @click="addOption(question)">
              <el-icon><Plus /></el-icon>添加选项
            </el-button>
          </el-form-item>

          <el-form-item label="是否必答">
            <el-switch v-model="question.required" />
          </el-form-item>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()

const surveyForm = reactive({
  title: '',
  description: '',
  endTime: null,
  type: 'public',
  questions: []
})

const addQuestion = () => {
  surveyForm.questions.push({
    type: 'single',
    content: '',
    required: false,
    options: []
  })
}

const removeQuestion = (index) => {
  surveyForm.questions.splice(index, 1)
}

const moveQuestion = (index, direction) => {
  const newIndex = index + direction
  if (newIndex >= 0 && newIndex < surveyForm.questions.length) {
    const temp = surveyForm.questions[index]
    surveyForm.questions[index] = surveyForm.questions[newIndex]
    surveyForm.questions[newIndex] = temp
  }
}

const addOption = (question) => {
  question.options.push({ content: '' })
}

const removeOption = (question, index) => {
  question.options.splice(index, 1)
}

const handleSave = async () => {
  try {
    // 验证表单
    if (!surveyForm.title) {
      ElMessage.warning('请输入问卷标题')
      return
    }

    // 验证问题
    if (surveyForm.questions.length === 0) {
      ElMessage.warning('请至少添加一个问题')
      return
    }

    // 验证每个问题
    for (let i = 0; i < surveyForm.questions.length; i++) {
      const question = surveyForm.questions[i]
      if (!question.content) {
        ElMessage.warning(`第${i + 1}个问题内容不能为空`)
        return
      }

      // 验证选项
      if (['single', 'multiple'].includes(question.type)) {
        if (!question.options || question.options.length < 2) {
          ElMessage.warning(`第${i + 1}个问题至少需要两个选项`)
          return
        }

        // 验证选项内容
        for (let j = 0; j < question.options.length; j++) {
          if (!question.options[j].content) {
            ElMessage.warning(`第${i + 1}个问题的第${j + 1}个选项内容不能为空`)
            return
          }
        }
      }
    }

    const response = await axios.post('http://localhost:3000/api/surveys', {
      title: surveyForm.title,
      description: surveyForm.description,
      end_time: surveyForm.endTime,
      type: surveyForm.type,
      questions: surveyForm.questions,
      status: 'draft' // 保存为草稿
    })
    
    ElMessage.success('问卷保存成功')
    // 保存成功后跳转到问卷列表页
    router.push('/surveys')
  } catch (error) {
    console.error('保存问卷失败:', error)
    ElMessage.error(`保存问卷失败: ${error.response?.data?.message || '请检查网络连接'}`)
  }
}

const handlePublish = async () => {
  try {
    // 验证表单
    if (!surveyForm.title) {
      ElMessage.warning('请输入问卷标题')
      return
    }

    // 验证问题
    if (surveyForm.questions.length === 0) {
      ElMessage.warning('请至少添加一个问题')
      return
    }

    // 验证每个问题
    for (let i = 0; i < surveyForm.questions.length; i++) {
      const question = surveyForm.questions[i]
      if (!question.content) {
        ElMessage.warning(`第${i + 1}个问题内容不能为空`)
        return
      }

      // 验证选项
      if (['single', 'multiple'].includes(question.type)) {
        if (!question.options || question.options.length < 2) {
          ElMessage.warning(`第${i + 1}个问题至少需要两个选项`)
          return
        }

        // 验证选项内容
        for (let j = 0; j < question.options.length; j++) {
          if (!question.options[j].content) {
            ElMessage.warning(`第${i + 1}个问题的第${j + 1}个选项内容不能为空`)
            return
          }
        }
      }
    }

    const response = await axios.post('http://localhost:3000/api/surveys', {
      title: surveyForm.title,
      description: surveyForm.description,
      end_time: surveyForm.endTime,
      type: surveyForm.type,
      questions: surveyForm.questions,
      status: 'active' // 发布为活动状态
    })
    
    ElMessage.success('问卷发布成功')
    // 发布成功后跳转到问卷列表页
    router.push('/surveys')
  } catch (error) {
    console.error('发布问卷失败:', error)
    ElMessage.error(`发布问卷失败: ${error.response?.data?.message || '请检查网络连接'}`)
  }
}
</script>

<style scoped>
.create-survey {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.survey-form {
  max-width: 800px;
  margin: 0 auto;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.question-title {
  font-weight: bold;
  font-size: 16px;
}

.option-item {
  margin-bottom: 10px;
}
</style>